package com.itheima.exception;

import com.itheima.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//切面
@Aspect
//被扫描
@Component
public class TransfarAdvice {
    //注入
    @Autowired
    private LogService logService;

    //切点
    @Pointcut("execution(* com.itheima.service.AccountService.transfer(..))")
    public void pu(){}
//    @Around("pu()")
//    public Object around(ProceedingJoinPoint joinPoint){
//        Object[] args = joinPoint.getArgs();
//        String out = args[0].toString();
//        String in = args[1].toString();
//        double v = Double.parseDouble(args[2].toString());
//        Object proceed = null;
//        try {
//            proceed = joinPoint.proceed();
//            String info = "添加成功";
//            logService.log(out,in,v,info);
//        } catch (Throwable e) {
//            String info = "添加失败";
//            logService.log(out,in,v,info);
//            throw new RuntimeException("转账失败");
//        }
//        return proceed;
//    }
    //1.返回通知
    @AfterReturning(value = "pu()",returning = "obj")
    public void returning(JoinPoint point, Object obj){
        //获取参数
        Object[] args = point.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());

        //返回通知的记录- 成功 (！！！！注入logService)
        String info = "转账成功！";
        System.out.println(info);
        logService.log(out,in,money,info);
    }
    //2. 异常通知
    @AfterThrowing(value = "pu()",throwing = "t")
    public void throwing(JoinPoint point,Throwable t){
        // 1. 获取参数
        Object[] args = point.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());
           // 3.2. 异常通知 - 失败原因
        String info = "转账失败,"+t.getMessage();
        System.out.println(info);
        logService.log(out,in,money,info);
    }
}
